{% extends "base.html" %}

{% block title %}我负责的任务{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>我负责的任务</h2>
        <div>
            <a href="{{ url_for('main.home') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-2"></i>返回首页
            </a>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="mb-0">任务列表</h5>
                </div>
                <div class="col-md-6 text-end">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary active" onclick="filterTasks('all')">全部</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterTasks('未开始')">未开始</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterTasks('进行中')">进行中</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterTasks('已完成')">已完成</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="card-body">
            {% if tasks %}
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>任务名称</th>
                                <th>项目</th>
                                <th>状态</th>
                                <th>优先级</th>
                                <th>进度</th>
                                <th>截止日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for task in tasks %}
                                <tr data-status="{{ task.status }}">
                                    <td>
                                        <a href="{{ url_for('project.project_detail', id=task.project_id) }}#task-{{ task.id }}">{{ task.name }}</a>
                                        {% if task.description %}
                                            <small class="d-block text-muted">{{ task.description[:50] }}{% if task.description|length > 50 %}...{% endif %}</small>
                                        {% endif %}
                                    </td>
                                    <td>{{ task.project.name }}</td>
                                    <td>
                                        {% if task.status == '未开始' %}
                                            <span class="badge bg-secondary">{{ task.status }}</span>
                                        {% elif task.status == '进行中' %}
                                            <span class="badge bg-primary">{{ task.status }}</span>
                                        {% elif task.status == '已完成' %}
                                            <span class="badge bg-success">{{ task.status }}</span>
                                        {% else %}
                                            <span class="badge bg-danger">{{ task.status }}</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if task.priority == '高' %}
                                            <span class="badge bg-danger">{{ task.priority }}</span>
                                        {% elif task.priority == '中' %}
                                            <span class="badge bg-warning">{{ task.priority }}</span>
                                        {% else %}
                                            <span class="badge bg-info">{{ task.priority }}</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar" role="progressbar" style="width: {{ task.progress }}%;" 
                                                 aria-valuenow="{{ task.progress }}" aria-valuemin="0" aria-valuemax="100">
                                                {{ task.progress }}%
                                            </div>
                                        </div>
                                    </td>
                                    <td>{{ task.end_date.strftime('%Y-%m-%d') if task.end_date else '-' }}</td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <a href="{{ url_for('task.task_form', id=task.id) }}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button class="btn btn-sm btn-outline-success" onclick="toggleTaskFollow({{ task.id }})">
                                                <i class="fas fa-star"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-info" onclick="showWorkHourForm({{ task.id }}, '{{ task.name }} ({{ task.project.name }})')">
                                                <i class="far fa-clock"></i> 工时填报
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-tasks fa-3x text-muted mb-3"></i>
                    <h5>暂无任务</h5>
                    <p class="text-muted">您目前没有负责任何任务</p>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 工时填报弹窗模态框 -->
<div class="modal fade" id="workHourModal" tabindex="-1" aria-labelledby="workHourModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="workHourModalLabel">工时填报</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="workHourForm" method="post" action="{{ url_for('work_hour.create') }}">
                    <input type="hidden" id="modalTaskId" name="task_id">
                    
                    <div class="mb-3">
                        <label class="form-label">任务</label>
                        <input type="text" class="form-control" id="modalTaskName" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label for="modalWorkHours" class="form-label">工时（小时） <span class="text-danger">*</span></label>
                        <input class="form-control" id="modalWorkHours" name="work_hours" type="number" step="0.5" min="0" max="24" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="modalWorkDate" class="form-label">工作日期 <span class="text-danger">*</span></label>
                        <input class="form-control" id="modalWorkDate" name="work_date" type="date" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="modalDescription" class="form-label">工作内容描述</label>
                        <textarea class="form-control" id="modalDescription" name="description" rows="4" placeholder="请描述完成的工作内容..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitWorkHourForm()">提交工时记录</button>
            </div>
        </div>
    </div>
</div>

<script>
function filterTasks(status) {
    // 更新按钮状态
    document.querySelectorAll('.btn-group .btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // 过滤任务
    const rows = document.querySelectorAll('tbody tr');
    rows.forEach(row => {
        if (status === 'all' || row.dataset.status === status) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

function toggleTaskFollow(taskId) {
    fetch(`/api/task_follow/${taskId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showFlashMessage(data.message, 'success');
            location.reload();
        } else {
            showFlashMessage('操作失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showFlashMessage('操作失败，请稍后重试', 'error');
    });
}

// 显示工时填报弹窗
function showWorkHourForm(taskId, taskName) {
    document.getElementById('modalTaskId').value = taskId;
    document.getElementById('modalTaskName').value = taskName;
    
    // 设置默认日期为今天
    const today = new Date();
    const formattedDate = today.toISOString().split('T')[0];
    document.getElementById('modalWorkDate').value = formattedDate;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('workHourModal'));
    modal.show();
}

// 提交工时表单
function submitWorkHourForm() {
    const form = document.getElementById('workHourForm');
    const workHours = document.getElementById('modalWorkHours').value;
    const workDate = document.getElementById('modalWorkDate').value;
    
    // 验证必填字段
    if (!workHours || !workDate) {
        showFlashMessage('请填写所有必填字段', 'error');
        return;
    }
    
    // 禁用提交按钮，防止重复提交
     const submitBtn = document.querySelector('#workHourModal button[type="submit"]');
     const originalText = submitBtn.textContent;
     submitBtn.disabled = true;
     submitBtn.textContent = '提交中...';
    
    // 提交表单
    fetch(form.action, {
        method: 'POST',
        body: new FormData(form),
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        // 恢复提交按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
        
        if (response.redirected) {
            // 如果服务器返回重定向，刷新页面
            window.location.reload();
            return;
        }
        return response.json().then(data => {
            return { response, data };
        }).catch(error => {
            // 如果响应不是JSON格式，可能是重定向或其他情况
            console.error('Response parsing error:', error);
            window.location.reload();
            throw error;
        });
    })
    .then(({ response, data }) => {
        if (data && data.success) {
            showFlashMessage('工时记录成功!', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('workHourModal'));
            modal.hide();
            // 重置表单
            form.reset();
            // 刷新页面以显示最新数据
            window.location.reload();
        } else if (data && !data.success) {
            showFlashMessage('工时记录失败: ' + (data.message || '未知错误'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showFlashMessage('工时记录失败，请稍后重试', 'error');
    });
}
</script>
{% endblock %}